package com.macrosolution.exdebito

import java.text.SimpleDateFormat;

import grails.converters.JSON;
import grails.plugin.springsecurity.annotation.Secured;

/**
 * ProfileController
 * A controller class handles incoming web requests and performs actions such as redirects, rendering views and so on.
 */
@Secured(['ROLE_ADMIN','ROLE_AMM','ROLE_BCKOFF','ROLE_AVV','ROLE_CC','ROLE_C','ROLE_SC','ROLE_CUSTOMER'])
class ProfileController {

	def springSecurityService
	
	static scaffold = true
	
	def info = {
		def secUser =springSecurityService.currentUser
		switch(request.method){
		  case "GET":
			[user:secUser]
			break;
		  case "POST":
			String born= params.born
			Long province =params.getLong('bornProvince')
			Long bornMunicipality =params.getLong('born_municipality')
			params.remove('bornProvince')
			params.remove('bornMunicipality')
			params.remove('born')
			secUser.setProperties(params)
			secUser.fiscalAddress.save(flush:true)
			
			if(born && !born.isEmpty()){
				secUser.born=new SimpleDateFormat('dd/MM/yyyy').parse(born)
			}
			if(province && province>0){
				secUser.bornProvince = Provincia.get(province)
			}
			if(bornMunicipality && bornMunicipality>0) {
				secUser.bornMunicipality = Comune.get(bornMunicipality)
				secUser.bornCap = (Comune.get(bornMunicipality)).cap
			}
			if (!secUser.save(flush: true)) {
				flash.message = 'Opppssss, Si è verificato un errore nel salvataggio dei tuoi dati'
				render view: 'info', model: [user: secUser]
				return
			}
			
			render view: 'info', model: [user: secUser,success:true]
			break;
		}
	}
	
	def password = { 
		switch(request.method){
			case "GET":
			break;
			case "POST":
			String password = params.password
			String newPassword = params.new_password
			String newPassword2 = params.re_new_password
			if (!password || !newPassword || !newPassword2 ){
				flash.message = 'Opppssss, Inserisci la password corrente o un nuova password valida'
				render view: 'password'
				return
			 }else if(newPassword != newPassword2) {
				 flash.message = 'Opppssss, Non hai confermato corretamente la password'
				 render view: 'password'
				 return
			 }
			 
			
			def user =springSecurityService.currentUser
	
			if (!springSecurityService.passwordEncoder.isPasswordValid(user.password, password, null))
			{
				flash.message = 'Oppsss, La password corrente non e\' corretta!'
				render view: 'password'
				return
			 }
			user.password=newPassword;
			user.save(flush:true)
			
			render view:'password' ,model:[success:true]
			break;
		}
	}
	
	def avatar ={
		
	}
	def reset_pass={
		User secUser =springSecurityService.currentUser
		secUser.password = secUser.originalPassword
		secUser.save(flush:true)
		def message="{'message':'La tua password è stata reimpostata con successo!'}"
		render JSON.parse(message) as JSON
	}
	
	
	
		
}
